package br.edu.planodesaude.GUI.procedimento;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

import br.edu.planodesaude.GUI.main.Exibir;
import br.edu.planodesaude.controle.Cadastradora;
import br.edu.planodesaude.controle.Pesquisadora;
import br.edu.planodesaude.dominio.Hospital;
import br.edu.planodesaude.dominio.Medico;
import br.edu.planodesaude.dominio.Procedimento;
import br.edu.planodesaude.dominio.Usuario;
import br.edu.planodesaude.exceptions.InsertionException;
import br.edu.planodesaude.exceptions.SearchException;
import br.edu.planodesaude.util.Formatadora;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author gustavo
 */
public class MarcarCirurgia extends javax.swing.JInternalFrame{

    private ArrayList<Medico> medicosRemoveArr = new ArrayList<Medico>();
	/**
     * Creates new form MarcarCirurgia
     */
    public MarcarCirurgia() {
    	setTitle("Marcar Cirurgia");
    	setVisible(true);
    	setClosable(true);
        initComponents();
        initHosp();
        initAddMed();
        initProc();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">      
	public void initHosp(){
		
		Object[] items = null;
		
		try{
			items = new Pesquisadora().getHospitais().toArray();
		}catch(SearchException sex){
			JOptionPane.showMessageDialog(null, sex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
		}
		
		DefaultComboBoxModel model = new DefaultComboBoxModel(items);
				
		hospitalJComboBox.setModel(model);
	}
	
	public void initAddMed(){
		modelAdd.clear();
		ArrayList<Medico> meds;
		try{
			meds = new Pesquisadora().getMedicos();
			for(Medico med : meds){
				modelAdd.addElement(med);
			}
		}catch(SearchException sex){
			JOptionPane.showMessageDialog(null, sex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
		}
		addJList.setModel(modelAdd);
	}
	
	public void initRemoveMed(ArrayList<Medico> medicos){
		DefaultListModel modelRemove = new DefaultListModel();
		
		for(Medico med : medicos){
			modelRemove.addElement(med);
		}
		removeJList.setModel(modelRemove);
	}
	
	public void initProc(){
		ArrayList<Procedimento> procs = new ArrayList<Procedimento>();
		
		try{
			procs = new Pesquisadora().getCirurgias();
		}catch(SearchException sex){
			JOptionPane.showMessageDialog(null, sex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
		}
		
		DefaultComboBoxModel model = new DefaultComboBoxModel(procs.toArray());
		
		cirurgiaJComboBox.setModel(model);
	}
    private void initComponents() {

        cpfJLabel = new javax.swing.JLabel();
        nomeJLabel = new javax.swing.JLabel();
        HospitalJLabel = new javax.swing.JLabel();
        medicosJLabel = new javax.swing.JLabel();
        cpfJFormattedTextField = new javax.swing.JFormattedTextField();
        hospitalJComboBox = new javax.swing.JComboBox();
        nomeJTextField = new javax.swing.JTextField();
        buscarJButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        addJList = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        removeJList = new javax.swing.JList();
        vinculaJButton = new javax.swing.JButton();
        removeJButton = new javax.swing.JButton();
        horarioJLabel = new javax.swing.JLabel();
        horariojFormattedTextField = new javax.swing.JFormattedTextField();
        marcarCirurgiaJButton = new javax.swing.JButton();
        cirurgiaJComboBox = new javax.swing.JComboBox();
        detalhesJButton = new javax.swing.JButton();
        cirurgiaJLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        cpfJLabel.setText("CPF");

        nomeJLabel.setText("Nome");

        HospitalJLabel.setText("Hospital");

        medicosJLabel.setText("Médico(s)");

        try {
            cpfJFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        buscarJButton.setText("Buscar");
        buscarJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscarJButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(addJList);

        jScrollPane2.setViewportView(removeJList);

        vinculaJButton.setText("Vincular");
        vinculaJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                vinculaJButtonActionPerformed(evt);
            }
        });

        removeJButton.setText("Remover");
        removeJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeJButtonActionPerformed(evt);
            }
        });

        horarioJLabel.setText("Horário");

        try {
            horariojFormattedTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/#### - ##h##min")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        marcarCirurgiaJButton.setText("Marcar Cirurgia");
        marcarCirurgiaJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                marcarCirurgiaJButtonActionPerformed(evt);
            }
        });

        detalhesJButton.setText("Detalhes");
        detalhesJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                detalhesJButtonActionPerformed(evt);
            }
        });

        cirurgiaJLabel.setText("Cirurgia");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(horarioJLabel)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(nomeJLabel)
                                .addGap(64, 64, 64)
                                .addComponent(nomeJTextField))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cpfJLabel)
                                    .addComponent(HospitalJLabel)
                                    .addComponent(medicosJLabel)
                                    .addComponent(cirurgiaJLabel))
                                .addGap(38, 38, 38)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(hospitalJComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cpfJFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(buscarJButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(horariojFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(0, 0, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(cirurgiaJComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                                            .addComponent(vinculaJButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(marcarCirurgiaJButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jScrollPane2)
                                            .addComponent(removeJButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(detalhesJButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))
                        .addGap(24, 24, 24))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cpfJLabel)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cpfJFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(buscarJButton)))
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(nomeJLabel)
                    .addComponent(nomeJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(53, 53, 53)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(HospitalJLabel)
                    .addComponent(hospitalJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(medicosJLabel)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vinculaJButton)
                    .addComponent(removeJButton))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cirurgiaJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(detalhesJButton)
                    .addComponent(cirurgiaJLabel))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(horarioJLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(horariojFormattedTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(marcarCirurgiaJButton)
                .addContainerGap())
        );

        setBounds(335, 105, 687, 517);
    }// </editor-fold>                        

    private void buscarJButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	
    	if(cpfJFormattedTextField.getText().equals("   .   .   -  ")){
    		JOptionPane.showMessageDialog(null, "Informe o CPF", "Alerta!", JOptionPane.WARNING_MESSAGE);
    	}else{
    		try{
    			us = new Pesquisadora().pesquisarUsuario(cpfJFormattedTextField.getText());
    			nomeJTextField.setText(us.getNome());
    			cpfJFormattedTextField.setEditable(false);
    			nomeJTextField.setEditable(false);
    		}catch(SearchException sex){
    			JOptionPane.showMessageDialog(null, sex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
    		}
    	}
    }                                             

    private void vinculaJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
        if(addJList.getSelectedValue() == null){
        	JOptionPane.showMessageDialog(null, "Nenhum médico selecionado!", "Alerta!", JOptionPane.WARNING_MESSAGE);
        }else{
        	Medico med = (Medico)addJList.getSelectedValue();
        	
        	if(!medicosFaraoProced.contains(med)){
        		medicosFaraoProced.add(med);
        		initRemoveMed(medicosFaraoProced);
        	}else{
        		JOptionPane.showMessageDialog(null, "Médico já vinculado", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        	}
        }
    }                                              

    private void removeJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
    	if(removeJList.getSelectedValue() == null){
        	JOptionPane.showMessageDialog(null, "Nenhum médico selecionado!", "Alerta!", JOptionPane.WARNING_MESSAGE);
        }else{
        	Medico medico = (Medico)removeJList.getSelectedValue();
        	medicosFaraoProced.remove(medico);
        	initRemoveMed(medicosFaraoProced);
        }
    }                                             

    private void detalhesJButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	Procedimento proced = (Procedimento)cirurgiaJComboBox.getSelectedItem();
    	String str = String.format("Nome: %s\nPreço: %.2f\nEspecialidade: %s\n", proced.getNome(), proced.getPreco(), proced.getEspecialidade().getNome());
        new Exibir(Formatadora.format(str, 62)).setVisible(true);
    }                                               

    private void marcarCirurgiaJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                      
    	if(cpfJFormattedTextField.getText().equals("   .   .   -  ")){
    		JOptionPane.showMessageDialog(null, "Informe o CPF", "Alerta!", JOptionPane.WARNING_MESSAGE);
    	}else if(medicosFaraoProced.isEmpty()){
    		JOptionPane.showMessageDialog(null, "Vincule ao menos um médico!", "Alerta!", JOptionPane.WARNING_MESSAGE);
    	}else if(horariojFormattedTextField.getText().equals("  /  /     -   h  min")){
    		JOptionPane.showMessageDialog(null, "Insira um horário!", "Alerta!", JOptionPane.WARNING_MESSAGE);
    	}else{
    		try{
    			Procedimento proc = (Procedimento)cirurgiaJComboBox.getSelectedItem();
    			Hospital hosp = (Hospital) hospitalJComboBox.getSelectedItem();
    			String str = horariojFormattedTextField.getText().replace('h', ':');
    			str = str.replaceAll("min", "");
    			Timestamp data = new Timestamp((new SimpleDateFormat("dd/MM/yyyy - hh:mm").parse(str).getTime()));
    			new Cadastradora().marcarCirurgia(us, hosp, medicosFaraoProced, proc, data);
    			JOptionPane.showMessageDialog(null, "Cirurgia marcada com sucesso!", "Alerta!", JOptionPane.INFORMATION_MESSAGE);
    			dispose();
    		}catch(InsertionException iex){
    			JOptionPane.showMessageDialog(null, iex.getMessage(), "Alerta!", JOptionPane.WARNING_MESSAGE);
    		}catch(ParseException pex){
    			JOptionPane.showMessageDialog(null, "Insira um horário válido!", "Alerta!", JOptionPane.WARNING_MESSAGE);
    		}
    	}
    }                                                     

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MarcarCirurgia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MarcarCirurgia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MarcarCirurgia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MarcarCirurgia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MarcarCirurgia().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel HospitalJLabel;
    private javax.swing.JList addJList;
    private javax.swing.JButton buscarJButton;
    private javax.swing.JComboBox cirurgiaJComboBox;
    private javax.swing.JLabel cirurgiaJLabel;
    private javax.swing.JFormattedTextField cpfJFormattedTextField;
    private javax.swing.JLabel cpfJLabel;
    private javax.swing.JButton detalhesJButton;
    private javax.swing.JLabel horarioJLabel;
    private javax.swing.JComboBox hospitalJComboBox;
    private javax.swing.JFormattedTextField horariojFormattedTextField;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton marcarCirurgiaJButton;
    private javax.swing.JLabel medicosJLabel;
    private javax.swing.JLabel nomeJLabel;
    private javax.swing.JTextField nomeJTextField;
    private javax.swing.JButton removeJButton;
    private javax.swing.JList removeJList;
    private javax.swing.JButton vinculaJButton;
    private static DefaultListModel modelAdd = new DefaultListModel();
    private static DefaultListModel modelRemove = new DefaultListModel();
    private ArrayList<Medico> medicosFaraoProced = new ArrayList<Medico>();
    private Usuario us;
    // End of variables declaration                   
}